package com.danskin.wechat.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.github.pagehelper.util.StringUtil;
import com.danskin.wechat.entity.CategoryProduct;
import com.danskin.wechat.entity.ProductGroupon;
import com.danskin.wechat.entity.ProductInfo;
import com.danskin.wechat.entity.WxCardConfig;
import com.danskin.wechat.service.CategoryProductService;
import com.danskin.wechat.service.ProductGrouponService;
import com.danskin.wechat.service.ProductInfoService;
import com.danskin.wechat.service.WxCardConfigService;
import com.danskin.wechat.util.FTPHelper;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;
/***
 * 商品
 * @author admin
 *
 */
@Controller
@RequestMapping("productInfo")
public class ProductInfoController extends BaseController{
    @Resource
    private ProductInfoService  productInfoService;
    @Resource
    private CategoryProductService  categoryProductService;
    @Resource
    private WxCardConfigService wxCardConfigService;
    @Resource
    private ProductGrouponService productGrouponService;
    /**
     * 每月团购
     * @return
     */
    @RequestMapping(value = "openProductInfo",method = RequestMethod.GET)
    public String openProductInfo(Model model){
    	List<CategoryProduct> categoryProduct = categoryProductService.findCategoryProduct(this.getMpId());
    	model.addAttribute("categoryProduct", categoryProduct);
    	return "product/openProduct";
    }
    /***
     * 当月精选
     * @return
     */
    @RequestMapping(value = "openProductGroupon",method = RequestMethod.GET)
    public String openProductGroupon(Model model){
    	List<CategoryProduct> categoryProduct = categoryProductService.findCategoryProduct(this.getMpId());
    	model.addAttribute("categoryProduct", categoryProduct);
    	return "product/openProductGroupon";
    }
    /***
     * 团购商品列表
     * @param carouselInfo
     * @param model
     * @return
     */
    @RequestMapping(value = "queryProductInfoList", method = RequestMethod.GET)
	public String queryProductInfoList(ProductInfo productInfo,Model model){
    	/*List<CategoryProduct> categoryProduct = categoryProductService.findCategoryProduct();
    	model.addAttribute("categoryProduct", categoryProduct);*/
		return "product/productInfo_tuan_list";
	}
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProductInfoList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object getProductInfoList(Page page,HttpServletRequest request) throws Exception {
    	Map map = getRequestParameter(this.getRequest());
		map.put("mpId", this.getMpId());
		page.setMap(map);
		List<ProductGroupon>  listGroupon = productGrouponService.findProductGrouponList(page);
		return pagelistToJSONForBootStrapTable(listGroupon, page);
	}
    /***
     * 修改数据(每月团购)
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "editProductInfo",method = RequestMethod.GET)
    public String  editProductInfo(HttpServletRequest request,Model model){
    	List<CategoryProduct> categoryProduct = categoryProductService.findCategoryProduct(this.getMpId());
    	String id = request.getParameter("id");
    	ProductGroupon productGroupon = null;
		if(StringUtil.isNotEmpty(id)){
			productGroupon = productGrouponService.findProductGrouponbyId(id);
		}
		model.addAttribute("productGroupon", productGroupon);
		model.addAttribute("categoryProduct", categoryProduct);
		if(productGroupon.getType().equals("1")){
			return "product/updateProduct";
		}else{
			return "product/updateProductGroupon";
		}
    }
    /***
     * 保存新增商品数据(当月或团购)
     * @param productInfo
     * @return
     * @throws IOException 
     * @throws IllegalStateException 
     */
    @RequestMapping(value = "saveProductGroupon",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    public String saveProductGroupon(HttpServletRequest request,ProductGroupon productGroupon,@RequestParam("picture") MultipartFile [] file) throws IllegalStateException, IOException{
    	int id = productGroupon.getId();
    	String oneImg = request.getParameter("oneImg");
    	String twoImg = request.getParameter("twoImg");
    	String details = productGroupon.getDetails();
    	List<File>  files = null;
    	if(StringUtil.isNotEmpty(details)){
    		files= this.getPathImg(details,request);
    	}
		String regex = "src=\"(.*?)\"";
		String detail=null;
		String[] split=null;
		if(StringUtils.isNotBlank(details)){
			split= details.split(regex);
			if(split.length>0){
				detail=split[0];
			}
		}
    	Map mapUrl = FTPHelper.getInstance().uploadPictureAndReturnPictureUrlList(file, "product",
    				FTPHelper.uploadTemporaryFile(),0);	
    	String detailsSetting = null;
    	try {
			//新增
    		if(files!=null){
    			String[] pictureUrl=new String[files.size()];
    			for(int i=0;i<files.size();i++){
        			int k=i+1;
        			FileInputStream input = new FileInputStream(files.get(i)); 
        	    	MultipartFile multipartFile = new MockMultipartFile("file", files.get(i).getName(), "text/plain", IOUtils.toByteArray(input));            			
        	    	pictureUrl[i]=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(multipartFile, "groupProductInfoGroup",
        					files.get(i).getCanonicalPath().substring(0, (files.get(i).getCanonicalPath().lastIndexOf(File.separator))));    
        			detail+="src=\""+pictureUrl[i]+"\""+split[k];
        		}
    		}
    		detailsSetting = detail;
		} catch (Exception e) {
			detailsSetting = details;
		}
    	if(id!=0){
    		//修改
    		ProductGroupon updateModel = getObjectUTF(productGroupon,"1",detailsSetting,oneImg,twoImg,mapUrl);
    		productGrouponService.updateProductGroupon(updateModel);
    	}else{
    		ProductGroupon  addModel = getObjectUTF(productGroupon,"2",detailsSetting,oneImg,twoImg,mapUrl);
    		productGrouponService.saveProductGroupon(addModel);
    	}
    	return "redirect:/productInfo/queryProductInfoList"; 
    }
    /**
     * 获取产品信息
     * @param productIn
     * @param type
     * @param pathURL
     * @return
     * @throws UnsupportedEncodingException
     */
	public ProductGroupon getObjectUTF(ProductGroupon productGroupon,String type,String detailsSetting,String oneImg,String twoImg,Map mapUrl) throws UnsupportedEncodingException{
		ProductGroupon pGroupon = new ProductGroupon();
    	if("1".equals(type)){
    		pGroupon.setId(productGroupon.getId());
    		pGroupon.setDetails(detailsSetting); 
    		if(StringUtil.isNotEmpty(oneImg)&&StringUtil.isNotEmpty(twoImg)){
    			pGroupon.setIconImg(mapUrl.get(1).toString());
    			pGroupon.setDetailImg(mapUrl.get(0).toString());
    		}else if(StringUtil.isNotEmpty(oneImg)){
    			pGroupon.setDetailImg(mapUrl.get(0).toString());
    		}else if(StringUtil.isNotEmpty(twoImg)){
    			pGroupon.setIconImg(mapUrl.get(1).toString());
    		}
    	}else{
    		pGroupon.setIconImg(mapUrl.get(0).toString());
    		pGroupon.setDetailImg(mapUrl.get(1).toString());
    		pGroupon.setDetails(detailsSetting); 
    	}
    	pGroupon.setMpId(this.getLoginUser().getMpId());
    	pGroupon.setCategoryId(productGroupon.getCategoryId());
    	pGroupon.setName(productGroupon.getName());
    	pGroupon.setSku(productGroupon.getSku());
    	pGroupon.setType(productGroupon.getType());
    	pGroupon.setOriginPrice(productGroupon.getOriginPrice());
    	pGroupon.setSalePrice(productGroupon.getSalePrice());
    	pGroupon.setStockQty(productGroupon.getStockQty());
    	pGroupon.setSaleStatus(productGroupon.getSaleStatus());
    	pGroupon.setSort(productGroupon.getSort());
    	pGroupon.setO2o(productGroupon.getO2o());
    	pGroupon.setTagInfo(productGroupon.getTagInfo());
    	pGroupon.setIsHot(productGroupon.getIsHot());
    	pGroupon.setCreatedTime(productGroupon.getCreatedTime());
    	pGroupon.setLastModifiedTime(productGroupon.getLastModifiedTime());
    	return pGroupon;
    }
    /**
	 * 删除配置信息(积分商城)
	 */
	@RequestMapping(value = "deleteProductInfo", method = RequestMethod.POST)
	public  void  deleteProductInfo(HttpServletRequest request, HttpServletResponse response){
		boolean flag = false;
		String id = request.getParameter("id");
		if(StringUtil.isNotEmpty(id)){
			productInfoService.deleteProductInfo(id);
			flag = true;
		}
	    renderData(response, flag);
	}
	/***
	 * 删除(团购/精选)
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "deleteProductGroupon", method = RequestMethod.POST)
	public  void  deleteProductGroupon(HttpServletRequest request, HttpServletResponse response){
		boolean flag = false;
		String id = request.getParameter("id");
		if(StringUtil.isNotEmpty(id)){
			productGrouponService.deleteProductGrouponModel(id);
			flag = true;
		}
	    renderData(response, flag);
	}
	/***s
	 * 商品管理(积分商城)
	 * @param productInfo
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "queryProductInfoMallList", method = RequestMethod.GET)
	public String queryProductInfoMallList(ProductInfo productInfo,Model model){
		List<CategoryProduct> list = categoryProductService.findCategoryProduct(this.getMpId());
		model.addAttribute("list", list);
		return "product/productInfo_mall_list";
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProductInfoMallList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object getProductInfoMallList(Page page,HttpServletRequest request) throws Exception {
		String type = "mall";
		Map map = getRequestParameter(this.getRequest());
		map.put("mpId", this.getMpId());
		page.setMap(map);
		List<ProductInfo> listProductInfo = productInfoService.findProductInfoList(page,type);
		return pagelistToJSONForBootStrapTable(listProductInfo, page);
	}
	/**
	 * 添加商品(积分商城)
	 * @return
	 */
	@RequestMapping(value = "openProductInfoMall",method = RequestMethod.GET)
    public String openProductInfoMall(Model model){
		//List<CategoryProduct> list = categoryProductService.findCategoryProduct();
		List<WxCardConfig> wxCardConfigList = wxCardConfigService.selectListForGiftConfig(this.getMpId());
		model.addAttribute("wxCardConfigList", wxCardConfigList);
    	return "product/openProductMall";
    }
	/***
	 * 积分商城(商品添加)
	 * @param request
	 * @param productInfo
	 * @param file
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "productInfoFormMall",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	public  String  productInfoFormMall(HttpServletRequest request,ProductInfo productInfo,@RequestParam("picture") MultipartFile file) throws IllegalStateException, IOException{
	    String details = productInfo.getDetails();
	    String typePro = request.getParameter("prodT");
	    List<File>  files= null;
	    if(StringUtil.isNotEmpty(details)){
	    	files= this.getPathImg(details,request);
	    }
		String regex = "src=\"(.*?)\"";
		String detail=null;
		String[] split=null;
		if(StringUtils.isNotBlank(details)){
			split= details.split(regex);
			if(split.length>0){
				detail=split[0];
			}
		}
		int id = productInfo.getId();
		String pictureUrl1 = null;
		if(productInfo.getProdType()==2){
			productInfo.setCouponTemplateId("");
		}
		if(!file.isEmpty()){
			// 上传图片到ftp服务器并返回图片地址
	    	pictureUrl1 = FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file, "product",
	    			FTPHelper.uploadTemporaryFile());
		}
		try {
    		//新增
	    	if(files!=null){
	    		String[] pictureUrl=new String[files.size()];
	    		for(int i=0;i<files.size();i++){
					int k=i+1;
					FileInputStream input = new FileInputStream(files.get(i)); 
			    	MultipartFile multipartFile = new MockMultipartFile("file", files.get(i).getName(), "text/plain", IOUtils.toByteArray(input));
					
			    	pictureUrl[i]=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(multipartFile, "integralMall",
							files.get(i).getCanonicalPath().substring(0, (files.get(i).getCanonicalPath().lastIndexOf(File.separator))));
					detail+="src=\""+pictureUrl[i]+"\""+split[k];
				}
	    	}	
	    	productInfo.setDetails(detail); 
		} catch (Exception e) {
			productInfo.setDetails(details); 
		} 
	    if(id!=0){
	    	//修改
    		productInfo.setImg(pictureUrl1);
    		productInfo.setProdType(Integer.parseInt(typePro));
    		productInfo.setMpId(this.getLoginUser().getMpId());     	
        	productInfo.setDetails(details);    				
	    	productInfoService.updateProductInfo(productInfo,"mall");
	    }else{	    	 	
    		productInfo.setImg(pictureUrl1);
	    	productInfo.setMpId(this.getLoginUser().getMpId());
	    	productInfo.setType("3");
	    	productInfoService.saveProductInfoModel(productInfo,"mall");
	    }
		return "redirect:/productInfo/queryProductInfoMallList"; 
	}
	/**
	 * 获取富文本编辑器上传的图片
	 * @param request
	 * @return
	 */
	public List<File> getPathImg(String path,HttpServletRequest request){
		String[] p=getImgaddress(path);
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHH");
		List<File> files = new ArrayList<File>();
		String servletPath = "/umeditor/jsp/upload/"+formater.format(new Date());
		if(p.length>0){
			for(int i=0;i<p.length;i++){
				String realPath = request.getSession().getServletContext()
						.getRealPath(servletPath);
				File file = new File(realPath+"/"+p[i]);
				System.out.println(file.getPath());
				files.add(file);
			}
		}
        return files;
	}
	/**
     * 返回存有图片地址的数组
     * @param tar
     * @return
     */
    public static String[] getImgaddress(String tar){
        List<String> imgList = getImg(tar);
        String res[] = new String[imgList.size()];
        if(imgList.size()>0){
            for (int i = 0; i < imgList.size(); i++) {
                int begin = imgList.get(i).indexOf("\"")+1;
                int end = imgList.get(i).lastIndexOf("\"");
                String url[] = imgList.get(i).substring(begin,end).split("/");
                res[i]=url[url.length-1];
            }
        }else{
        }
        return res;
    }
    public static List<String> getImg(String s)
    {
        String regex;
        List<String> list = new ArrayList<String>();
        regex = "src=\"(.*?)\"";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(s);
        while (ma.find())
        {
            list.add(ma.group());
        }
        return list;
    }
	/***
	 * 修改商品信息(积分商城)
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editProductInfoMall",method = RequestMethod.GET)
	public String  editProductInfoMall(HttpServletRequest request,Model model){
	    String id = request.getParameter("id");
	    List<WxCardConfig> wxCardConfigList = wxCardConfigService.selectListForGiftConfig(this.getMpId());
	    ProductInfo productInfo = null;
		if(StringUtil.isNotEmpty(id)){
			productInfo = productInfoService.findProductInfobyId(id);
		}
		//List<CategoryProduct> list = categoryProductService.findCategoryProduct();
		model.addAttribute("productInfo", productInfo);
		model.addAttribute("wxCardConfigList", wxCardConfigList);
		return "product/editProductMall";
	}
	 
	private void renderData(HttpServletResponse response, boolean data) {
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(data);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}
	}
	/**
	 * 判断sku是否重复(积分商城)
	 * @param sku
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toCheckSku", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String toCheckSku(String sku,String type) throws Exception {
    	Map<String,Object> map=new HashMap<String, Object>();
    	List<ProductInfo> pList = productInfoService.queryProductInfoBySku(sku,type);
    	if(pList.size()>0){	
    		map.put("status", 400);
    		map.put("msg", "SKU编码重复");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "SKU编码可用");
    	}
    	return JsonUtils.objectToJson(map);
    }
    /**
	 * 判断sku是否重复(团购/当月精选)
	 * @param sku
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toCheckProductGrouponSku", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String toCheckProductGrouponSku(String sku,String type) throws Exception {
    	Map<String,Object> map=new HashMap<String, Object>();
    	List<ProductGroupon> pList = productGrouponService.queryProductGrouponSku(sku,type,this.getMpId());
    	if(pList.size()>0){	
    		map.put("status", 400);
    		map.put("msg", "SKU编码重复");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "SKU编码可用");
    	}
    	return JsonUtils.objectToJson(map);
    }
	/**
	 * 判断sort排序是否重复
	 * @param sku
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toCheckSort", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String toCheckSort(String sort) throws Exception {
    	Map<String,Object> map=new HashMap<String, Object>();
    	List<ProductInfo> cList = productInfoService.queryProductInfoBySort(sort,this.getMpId());
    	if(cList.size()>0){	
    		map.put("status", 400);
    		map.put("msg", "sort排序重复");
    	}else{
    		map.put("status", 200);
    		map.put("msg", "sort排序可用");
    	}
    	return JsonUtils.objectToJson(map);
    }
	//处理中文乱码
	public String getConversionUTF(String str) throws UnsupportedEncodingException{
		if(!"".equals(str)&&str!=null){
			str = new String(str.getBytes("iso-8859-1"), "UTF-8");
		}		
		return str;
	}
}

